package com.cysyz.mylib.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ShellUtils {
    static final Logger logger = LoggerFactory.getLogger(ShellUtils.class);

    public static int executeShell(String shellCommand) {
        int resultCode = 1;
        StringBuffer logContent = new StringBuffer();
        BufferedReader bufferedReader = null;
        //格式化日期时间，记录日志时使用
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS ");

        try {
            logContent.append(dateFormat.format(new Date())).append("准备执行Shell命令\n").append(shellCommand).append(" \r\n");

            Process process = null;
//            String[] cmd = {shellCommand};
            //执行Shell命令
            process = Runtime.getRuntime().exec(shellCommand);

            if (process != null) {
                logContent.append("进程信息：").append(process.toString()).append("\r\n");
                //bufferedReader用于读取Shell的输出内容 bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()), 1024);
                resultCode = process.waitFor();
            } else {
                logContent.append("没有pid\r\n");
            }

            if (resultCode == 0) {
                logContent.append(dateFormat.format(new Date())).append(" Shell命令执行成功\r\n执行结果为：\r\n");
            } else {
                logContent.append(dateFormat.format(new Date())).append(" Shell命令执行失败\r\n执行结果为：\r\n");
            }
            //读取Shell的输出内容，并添加到stringBuffer中
            BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = "";
            while ((line = input.readLine()) != null) {
                logContent.append(line).append("\n");
//                System.out.println(line);
            }
            logger.info(logContent.toString());
        } catch (Exception ioe) {
            logContent.append("执行Shell命令时发生异常：\r\n").append(ioe.getMessage()).append("\r\n");
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                    logger.info(logContent.toString());
                } catch (Exception e) {
                    logger.info("关闭流异常", e);
                }
            }
        }


        return resultCode;
    }
}  